<template>
  <div v-loading="initLoading">
    <el-table
      v-if="visible"
      ref="goodsTableRef"
      :data="goodsList"
      @selection-change="changeAll"
      row-key="id"
    >
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true"
      ></el-table-column>
      <el-table-column prop="goods_name" label="商品" width="380">
        <template #default="scope">
          <div class="flex">
            <el-avatar :src="scope.row.goods_image" :size="40" shape="square" />
            <div class="ml10">
              <div class="goods-name">{{ scope.row.goods_name }}</div>
              <div class="text-red">￥{{ scope.row.goods_price }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="goods_stock"
        label="库存"
        align="center"
        width="180"
      />
      <el-table-column prop="type" label="商品类型" />
    </el-table>
  </div>
  <!-- 分页 -->
  <div class="goods-list-page">
    <div>已选择 {{ selectedGoodsData.length }} 个商品</div>
    <page :listPage="listPage" @change="pageChange"></page>
  </div>
</template>
<script lang="ts">
export default {
  name: "selectGoodsCheckbox",
};
</script>
<script setup lang="ts">
import { ref, getCurrentInstance, watch, nextTick, onMounted } from "vue";
import { listPageType, Result, ResultError } from "@/types";
import { getGoodsSimpleList } from "@/api/store/goods";
import { useConfig } from "@/store";
import { ElTable } from "element-plus";

const configStore = useConfig();

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const props = withDefaults(
  defineProps<{
    ids: idsType;
    visible: boolean;
    data: any;
  }>(),
  {
    ids: () => {
      return [];
    },
    data: [],
    visible: false,
  }
);

type idsType = Array<string | number>;

const listPage = ref<listPageType>({
  total: 0,
  limit: configStore.getPageLimit,
  page: 1,
});

const pageChange = (res: listPageType) => {
  listPage.value = res;
  toInit();
};

const initLoading = ref<boolean>(true);

const goodsList = ref<any>([]);

// 获取商品
const toInit = (cateId: number = -1) => {
  if (cateId !== -1) {
    listPage.value.page = 1;
    searchData.value.cate_id = cateId;
  }
  let obj: any = {};

  obj.page = listPage.value.page;
  obj.limit = listPage.value.limit;
  initLoading.value = true;
  getGoodsSimpleList(Object.assign(obj, searchData.value))
    .then((res: Result) => {
      goodsList.value = res.data.data;
      listPage.value.total = res.data.total;
      initSelectedRow();
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const goodsTableRef = ref<InstanceType<typeof ElTable>>();

const selectedGoodsIds = ref<idsType>([]);

const selectedGoodsData = ref<any>([]);

// 初始化选择状态
const initSelectedRow = () => {
  console.log("默认选中数据：", props.ids, props.data);
  selectedGoodsIds.value = JSON.parse(JSON.stringify(props.ids));
  selectedGoodsData.value = JSON.parse(JSON.stringify(props.data));
  initLoading.value = false;
  nextTick(() => {
    goodsList.value.forEach((item: any) => {
      if ($utils.inArray(item.id, props.ids)) {
        goodsTableRef.value!.toggleRowSelection(item, true);
      }
    });
  });
};

// 筛选条件
const searchData = ref<{
  cate_id: number | string;
}>({
  cate_id: 0,
});

const changeAll = (selection: any) => {
  // 选择为空时
  if (selection.length === 0) {
    goodsList.value.forEach((item: any) => {
      if ($utils.inArray(item.id, selectedGoodsIds.value)) {
        delData(item);
        delId(item);
      }
    });
  } else {
    // 当前表格
    goodsList.value.forEach((item: any) => {
      // 当前表格处理前选择
      var selectIndex = $utils.arrayFilterMultiple(selection, "id", item.id);
      // 当前表格选择
      if (selectIndex !== -1) {
        // 把选择数据item追加在selectedGoodsData
        if (
          $utils.arrayFilterMultiple(selectedGoodsData.value, "id", item.id) ===
          -1
        ) {
          selectedGoodsData.value.push(item);
        }
        // 把选择数据id追加在selectedGoodsIds
        if (
          $utils.arrayFilterMultiple(selectedGoodsIds.value, false, item.id) ===
          -1
        ) {
          selectedGoodsIds.value.push(item.id);
        }
      } else {
        // 没选择的数据 需做删除处理
        if (
          $utils.arrayFilterMultiple(selectedGoodsData.value, "id", item.id) !==
          -1
        ) {
          delData(item);
        }
        if (
          $utils.arrayFilterMultiple(selectedGoodsIds.value, false, item.id) !==
          -1
        ) {
          delId(item);
        }
      }
    });
  }
};

// 删除数据
const delData = (item: any) => {
  selectedGoodsData.value.splice(
    $utils.arrayFilterMultiple(selectedGoodsData.value, "id", item.id),
    1
  );
};

// 删除id
const delId = (item: any) => {
  selectedGoodsIds.value.splice(
    $utils.arrayFilterMultiple(selectedGoodsIds.value, false, item.id),
    1
  );
};

const getData = () => {
  return {
    ids: selectedGoodsIds.value,
    data: selectedGoodsData.value,
  };
};

defineExpose({ toInit, getData });
</script>

<style scoped>
.goods-list-page {
  position: absolute;
  width: calc(100% - 20px);
  background: #ffffff;
  bottom: 0;
  left: 10px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.goods-name {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>